import React from 'react';
import { Divider, message, Modal } from 'antd';
import { FormattedMessage } from 'umi';
import ATable, { ATableProps } from '@/components/SelfComp/ATable';
import AToolBar, { AToolBarProps }  from '@/components/SelfComp/AToolBar';
import { getButton } from '@/utils/authority';
import { ButtonItem } from '@/utils/Auth';

type AGridProps<RecordType extends object = any> = ATableProps & AToolBarProps & {
  /** 页面编码 */
  code: string;
  /** 按钮点击回调函数 */
  btnCallBack?: Function;
  /** 删除时定制提示语，非必输 */
  delConfirmMsg?: string;
  /** 表格作为唯一标识的字段，非必输 */
  pkField?: string;
  childPkField?: string;
  /** 表格操作列自定义按钮函数，非必输 */
  renderActionButton?: Function;
  /** 表格操作列的宽度，非必输，不填时默认为100 */
  actionColumnWidth?: number;
  /** 表格操作列是否固定，非必输 */
  actionColumnFixed?: true| 'left' | 'right';
  /** 是否需要操作列，不需要写true */
  noActionColumn?: boolean;
};

/** 这里将onChange去掉，改成自己的方法 */
// type AGridPropsEx = Omit<AGridProps, 'onChange'>;

interface AGridState<TableDataType> {
  current: number;
  size: number;
  formValues: {};
  selectedRows: TableDataType[];
  selectedRowKeys: React.Key[];
  /** 当前页面的按钮集合 */
  stateButtons: ButtonItem[];
  columnButtons: ButtonItem[];
}

export interface AGridButtonCallBackModel<TableDataType> {
  btn: ButtonItem;
  keys: React.Key[];
  rows: TableDataType[];
  refresh?: Function;
}

/**
 * 表格的简单封装，添加表头按钮及默认操作列
 */
export default class AGrid<TableDataType extends object> extends React.PureComponent<AGridProps, AGridState<TableDataType>> {

  constructor(props: AGridProps) {
    super(props);
    this.state = {
      current: 1,
      size: 10,
      formValues: {},
      selectedRows: [],
      selectedRowKeys: [],
      // 全量的按钮集合
      stateButtons: getButton(props.code),
      columnButtons: []
    };
  }

  /**
   * 获取表格勾选内容
   * @returns 返回表格选择的key
   */
  getSelectKeys = () => {
    // const { selectedRows } = this.state;
    // const { pkField = 'id', childPkField = 'id' } = this.props;
    // return selectedRows.map(row => {
    //   const selectKey = row[pkField] || row[childPkField];
    //   if (`${selectKey}`.indexOf(',') > 0) {
    //     return `${selectKey}`.split(',');
    //   }
    //   return selectKey;
    // });
    const { selectedRowKeys } = this.state;
    return selectedRowKeys;
  };

  /**
   * 表格上方操作栏按钮点击事件处理
   * @param {*} btn 按钮
   */
  handleToolBarClick = (btn: ButtonItem) => {
    // console.log(btn);
    const { selectedRows } = this.state;
    const keys = this.getSelectKeys();
    this.handleClick(btn, keys, selectedRows);
  };

  /**
   * 表格勾选处理事件
   * @param selectedRowKeys 指定选中项的 key 数组
   * @param selectedRows 指定选中项数组
   */
  handleSelectRow = (selectedRowKeys: React.Key[], selectedRows: TableDataType[]) => {
    this.setState({
      selectedRowKeys,
      selectedRows
    });
    // 表格勾选事件回调，给父组件传递勾选数据
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRowKeys, selectedRows);
    }
  };

  /**
   * 表格按钮列点击事件处理
   * @param {*} btn 按钮属性
   * @param {*} keys 表格选中行key集合
   * @param {*} rows 表格选中行数据集合
   * @returns
   */
  handleClick = (btn: ButtonItem, keys: React.Key[] = [], rows: TableDataType[]) => {
    // console.info(`handleClick-${btn}`);
    // console.info(`btn-${JSON.stringify(btn)}`);
    // console.info(`keys-${JSON.stringify(keys)}`);
    // console.info(`rows-${JSON.stringify(rows)}`);
    const { alias } = btn;
    const { btnCallBack } = this.props;
    const refresh = (temp = false) => this.refreshTable(temp);
    if (alias === 'edit' || alias === 'view') {
      if (keys.length <= 0) {
        message.warn('请先选择一条数据！');
        return;
      }
      if (keys.length > 1) {
        message.warn('只能选择一条数据！');
        return;
      }
    }
    if (alias === 'add' || alias === 'edit' || alias === 'view') {
      if (btnCallBack) {
        const callBackModel: AGridButtonCallBackModel<TableDataType> = {
          btn,
          keys,
          rows,
          refresh
        }
        btnCallBack(callBackModel);
      }
    }
    if (alias === 'delete') {
      if (keys.length <= 0) {
        message.warn('请先选择要删除的记录！');
        return;
      }
      const { delConfirmMsg } = this.props;
      let confirmContent = '确定删除选中记录？';
      if (delConfirmMsg) {
        confirmContent = delConfirmMsg;
      }
      Modal.confirm({
        title: '删除确认',
        content: confirmContent,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => this.deleteBtnClick(btn, keys, rows, refresh),
        onCancel() {},
      });
      return;
    } else {
      if (btnCallBack) {
        const callBackModel: AGridButtonCallBackModel<TableDataType> = {
          btn,
          keys,
          rows,
          refresh
        }
        btnCallBack(callBackModel);
      }
    }
  };

  /**
   * 删除按钮点击事件
   * @param {*} btn 删除按钮
   * @param {*} keys 表格选中key值集合
   * @param {*} rows 表格选中
   */
  deleteBtnClick = (btn: ButtonItem, keys: React.Key[] = [], rows: TableDataType[], refresh: Function) => {
    const { btnCallBack } = this.props;
    if (btnCallBack) {
      const callBackModel: AGridButtonCallBackModel<TableDataType> = {
        btn,
        keys,
        rows,
        refresh
      }
      btnCallBack(callBackModel);
    }
  };

  refreshTable = (temp: boolean) => {
    console.info('refreshTable', temp)
  }

  render() {
    // AToolBar属性
    const { renderLeftButton, renderRightButton } = this.props;
    // ATable属性
    const {
      pkField,
      childPkField,
      actionColumnWidth,
      rowKey,
      dataSource,
      loading,
      total,
      // onShowSizeChange 高版本里该属性与onPageNumChange合并了
      // 改成 onPageNumAndSizeChange
      onPageNumAndSizeChange,
      // 额外的按钮
      renderActionButton,
      buttons,
      actionColumnFixed,
      scroll,
      noActionColumn,
    } = this.props;
    // 表格勾选数据，方便清除表格勾选
    const { selectedRows } = this.state;
    let { columns } = this.props;

    // 默认增删改查四个按钮
    let normalButtons: ButtonItem[] = [];
    if (!noActionColumn) {
      if (!buttons) {
        const { stateButtons } = this.state;
        // console.log(stateButtons);
        normalButtons = [...stateButtons];
      } else {
        normalButtons.push({
          action: '1',
          code: 'add',
          alias: 'add',
          name: '新增',
        });
      }
      // console.info(actionColumnFixed, actionColumnWidth);
      // 获取页面按钮集合中的修改，删除，查看
    // action 1 工具栏
    // action 2 表格列操作栏
    // action 3 工具及表格列操作栏
    const actionColumnButtons = normalButtons.filter(button => button && (button.action === '2' || button.action === '3'));
    // 表格列中最后新增一个操作列
    if (columns && Array.isArray(columns) && (actionColumnButtons.length > 0 || renderActionButton)) {
      const key = pkField || 'id';
      // console.info(key);
      columns = [
        ...columns,
        {
          title: '操作',
          width: actionColumnWidth || 100,
          align: 'center',
          fixed: actionColumnFixed || 'left',
          render: (_, record) => {
            // console.info('actionColumn.render');
            // console.info(record);
            return (
              <React.Fragment>
                <div style={{ textAlign: 'center' }}>
                  {actionColumnButtons.map((button, index) => (
                    <React.Fragment key={button.code}>
                      {index > 0 ? <Divider type="vertical" /> : null}
                      <a
                        title={button.name}
                        onClick={() =>
                          this.handleClick(button, [record[key]], [record])
                        }
                      >
                        <FormattedMessage id={`button.${button.alias}.name`} />
                      </a>
                    </React.Fragment>
                  ))}
                  {renderActionButton
                    ? renderActionButton([record[childPkField || key]], [record])
                    : null}
                </div>
              </React.Fragment>
            );
          },
        },
      ];
    }
    }
    // const hasSelected = (selectedRowKeys.length == 1);
    return (
      <React.Fragment>
        <AToolBar
          buttons={normalButtons}
          renderLeftButton={renderLeftButton}
          renderRightButton={renderRightButton}
          onClick={this.handleToolBarClick}
        />
        <ATable<TableDataType>
          columns={columns}
          rowKey={rowKey}
          dataSource={dataSource}
          loading={loading}
          total={total}
          selectedRows={selectedRows}
          onSelectRow={this.handleSelectRow}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          scroll={scroll}
        />
      </React.Fragment>
    );
  }
}